import { createRouter, createWebHistory } from 'vue-router'
import { isAuthenticated } from '../stores/auth'
import HomePage from '../components/HomePage.vue'
import LoginForm from '../components/LoginForm.vue'
import RegisterForm from '../components/RegisterForm.vue'
import UsersList from '../components/UsersList.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: HomePage,
    },
    {
      path: '/login',
      name: 'Login',
      component: LoginForm,
      meta: { requiresGuest: true },
    },
    {
      path: '/register',
      name: 'Register',
      component: RegisterForm,
      meta: { requiresGuest: true },
    },
    {
      path: '/users',
      name: 'Users',
      component: UsersList,
      meta: { requiresAuth: true },
    },
  ],
})

// 路由守卫
router.beforeEach((to, _from, next) => {
  const authenticated = isAuthenticated.value

  // 需要认证的页面
  if (to.meta.requiresAuth && !authenticated) {
    next('/login')
    return
  }

  // 只允许游客访问的页面（如登录、注册）
  if (to.meta.requiresGuest && authenticated) {
    next('/users')
    return
  }

  next()
})

export default router
